#!/bin/bash
#mysql自动化安装脚本
#密码
password='Y4yhl9t@2022'
#数据库存储路径
data_path='/home/mysql/data'

echo "----- mysql自动化安装脚本开始执行 -----"
#卸载CentOS自带的mariadb依赖
rpm -qa|grep mariadb
if [ $? -eq 0 ];then
   rpm -e --nodeps mariadb-libs
   echo "----- 成功卸载mariadb-libs，脚本继续执行 -----"
else
   echo "----- mariadb-libs不存在，脚本继续执行 -----"
fi
#解压MySQL压缩包
echo "----- 解压MySQL压缩包 -----"
if [ ! -d "../temp/mysql-8.0.16" ];then
  mkdir ../temp/mysql-8.0.16
fi
tar xvf ../rpm/mysql-8.0.16-2.el7.x86_64.rpm-bundle.tar -C ../temp/mysql-8.0.16
if [ $? -eq 0 ];then
   echo "----- Mysql压缩包解压成功 -----"
else
   echo "----- Mysql压缩包解压失败，脚本退出 -----"
   exit 1
fi
#开始安装mysql
echo "----- 开始安装mysql -----"
rpm -ivh ../temp/mysql-8.0.16/mysql-community-common-8.0.16-2.el7.x86_64.rpm
rpm -ivh ../temp/mysql-8.0.16/mysql-community-client-plugins-8.0.16-2.el7.x86_64.rpm
rpm -ivh ../temp/mysql-8.0.16/mysql-community-libs*
rpm -ivh ../temp/mysql-8.0.16/mysql-community-client-8.0.16-2.el7.x86_64.rpm
rpm -ivh ../temp/mysql-8.0.16/mysql-community-server-8.0.16-2.el7.x86_64.rpm
#验证mysql是否安装成功
echo "----- 验证mysql是否安装成功 -----"
rpm -qa|grep mysql
if [ $? -eq 0 ];then
   echo "----- mysql安装成功 -----"
else
   echo "----- mysql安装失败，脚本退出 -----"
   exit 1
fi
#mysql授权
echo "----- mysql授权 -----"
if [ ! -d ${data_path} ];then
  mkdir -p ${data_path};
  chmod -R 777 /usr/sbin/mysqld;
  chmod -R 777 ${data_path};
  chmod -R mysql:mysql /usr/sbin/mysqld;
  chown -R mysql:mysql ${data_path};
fi
#替换配置文件
echo "----- 替换配置文件 -----"
mv /etc/my.cnf /etc/my.cnfbak
cp -f ../conf/my.cnf /etc/
#mysql初始化
echo "----- mysql初始化 -----"
mysqld --initialize --user=mysql;
#启动mysql服务，不然会获取不到mysql默认密码
echo "----- 启动mysql服务 -----"
systemctl start mysqld
if [ $? -eq 0 ];then
   echo "----- mysql启动成功 -----"
else
   echo "----- mysql启动失败，脚本退出 -----"
   exit 1
fi
#获取默认root密码
echo "----- 获取默认root密码 -----"
grep "password is generated" /var/log/mysqld.log | awk '{print $NF}' > ../temp/mysql-8.0.16/mysqlpassword.txt
if [ $? -eq 0 ];then
   echo "----- 获取默认密码成功，并追加到mysqlpassword.txt -----"
else
   echo "----- 获取默认密码失败，脚本退出 -----"
   exit 1
fi
#修改root密码,脚本内修改为y4yhl9t，可以自行替换
echo "----- 修改root密码，密码规则长度为8位，有大写字母、小写字母、特殊符号 -----"
psd=$(cat ../temp/mysql-8.0.16/mysqlpassword.txt)

mysql -uroot -p${psd} -e "alter user root@'localhost' identified with mysql_native_password by '${password}';" --connect-expired-password
#开启远程连接
mysql -uroot -p${password} <<EOF
use mysql;
create user root@'%' identified with mysql_native_password by '${password}';
grant all on *.* to root@'%' with grant option;
flush privileges;
exit
EOF
#开放3306端口访问权限
echo "----- 开放3306端口访问权限 -----"
systemctl start firewalld
if [ $? -eq 0 ];then
   echo "----- 成功开启防火墙 -----"
else
   echo "----- 防火墙开启失败，脚本退出 -----"
   exit 1
fi
firewall-cmd --zone=public --add-port=3306/tcp --permanent
if [ $? -eq 0 ];then
   firewall-cmd --reload
   echo "----- 3306端口开启成功 -----"
else
   echo "----- 3306端口开启失败，脚本退出 -----"
   exit 1
fi
echo "----- mysql自动化安装脚本执行完毕 -----"
